import React, { useState, useEffect, useMemo } from 'react';
import {
  Modal, Button, Skeleton, Image, message, Upload, Row, Col, Space, Tag, Tabs,
  Input,
  List,
  InputNumber
} from 'antd'
import { UploadOutlined, LoadingOutlined, CloseOutlined } from '@ant-design/icons';
import type { TabsProps } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { information } from '@/utils/rules';
import Utils from 'fr-util/utils';

import {
  ProFormText,
  ProForm,
  ProFormTextArea,
  ProFormSelect,
  ProFormDependency,
  ProCard,
  CheckCard
} from '@ant-design/pro-components';


import {
  reqPulseCalibrationList,
  reqTongueCalibrationList,
  reqDiagnosisTermList,
  reqDiagnosisTermListByGrade,
  reqSeniorInquiryList,
  reqSeniorInquiryUpdate,
  reqSymptomList,
  reqSymptomListByGrade,
  reqWesternMedicineList,
  reqBaseFormulaList,
  reqBaseFormulaDetailList,
  reqEtiologyCategoryList,
  reqEtiologyList,
  reqEtiologyCategoryListByDiagnosis,
  reqSeniorInquiryPrescriptionMedication,
  reqAggregationHotDataList,
} from '@/services/firstConsultation';

import styles from '../index.module.less'

const WesternMedicineList: React.FC = ({

  handleModal,
  user
}) => {

  const [data, setData] = useState([])

  const [selectList, setSelectList] = useState([])

  useEffect(() => {
    if (
      user?.westernMedicineList &&
      Array.isArray(user?.westernMedicineList) &&
      user?.westernMedicineList?.length > 0
    ) {

      // let newArr = user?.westernMedicineList.map((item) => {
      //   return {

      //   }
      // })
      setSelectList(user?.westernMedicineList)
    }
  }, [user])

  const [formObj] = ProForm.useForm()

  const initSize = { pageNum: 1, pageSize: 10 }

  const [newParam, setParam] = useState(initSize)

  const onValuesChange = async (params: any) => {
    // console.log('handleAdd=== :>> ', params);
    if (params?.parentId || params?.parentId2) {
      setParam(prev => ({ ...prev, parentId: params?.parentId2 || params?.parentId, ...initSize, type: 2 }))
    }
  }

  // 西药搜索字段
  const [searchKey, setSearchKey] = useState('')

  // 搜索西药列表
  function onSearchSelect(value: string) {
    console.log('onSearchSelect=== :>> ', value);
    setSearchKey(value)
    setParam(prev => ({ ...prev, name: value, ...initSize }))
  }


  // useEffect(() => {
  //   if (defArr && defArr?.length > 0 && data && data?.length > 0) {
  //     const initList = defArr.map((item: any) => item?.id)
  //     setSelectList(initList)
  //   }
  // }, [defArr, data])



  async function init(query = {}) {
    const errLogName = '西药信息列表'
    try {
      const res = await reqWesternMedicineList({ ...query })
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        setData(res?.data?.result)
      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }

  const [hotDataList, setHotDataList] = useState()

  async function getHotDataList(query = {}) {
    const errLogName = '常用数据列表'
    try {
      const res = await reqAggregationHotDataList({ ...query })
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        setHotDataList(res?.data?.result)
      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }



  useEffect(() => {
    init({ ...newParam, type: 2 })
    getHotDataList({
      pageNum: 1,
      pageSize: 10,
      // 类型，[1:中药,2:西药,3:汤剂,4:针灸]
      type: 2
    })
  }, [newParam])


  async function onKeep() {
    if (selectList?.length < 1) {
      message.error('请先添加一份西药再保存！')
      return;
    }

    const errLogName = '开药'
    try {
      const res = await reqSeniorInquiryPrescriptionMedication({
        id: user?.seniorInquiry?.id,
        receiveMethod: user?.receiveMethod,
        medicineType: 2,
        medicineList: selectList
      });
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        handleModal(false)
        message.success(`${errLogName}保存成功！`)
      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }

  }

  async function getList1(query = {}) {
    const res = await reqWesternMedicineList({ ...query, type: 1 });
    const mapArr = res?.data?.result?.map((item: any) => ({
      value: item?.id,
      label: item?.name,
    }))
    return mapArr;
  }

  // console.log('data :>> ', data);


  function onChangeNumber(value: number, item: any) {
    console.log('object :>> ', value, item);


    const arr = JSON.parse(JSON.stringify(selectList));
    const index = arr.findIndex((li: any) => li?.medicineId == item?.id);
    if (index > -1) {
      if (!value) {
        arr.splice(index, 1)
      } else {
        if (value > 0) {
          arr[index].quantity = value
        } else {
          arr.splice(index, 1)
        }
      }
    } else {
      if (value && value > 0) {
        arr.push({
          quantity: value,
          medicineId: item?.id
        })
      }
    }
    setSelectList(arr)
  }

  console.log('selectList :>> ', selectList);


  return (
    <div>
      <ProForm
        form={formObj}
        submitter={false}
        layout="horizontal"
        onValuesChange={(values): Promise<any> => onValuesChange(values)}
      >
        <Row gutter={24}>
          <Col span={6}>
            <ProFormSelect
              style={{ width: '100%' }}
              placeholder="请选择病症"
              label="一级分类"
              name='parentId'
              request={getList1}
            />
          </Col>
          <Col span={6}>
            <ProFormDependency
              name={['parentId']}
              shouldUpdate={(prevValues, curValues) => (
                prevValues.parentId !== curValues.parentId
              )}
            >
              {({ parentId }) => {
                return (
                  <ProFormSelect
                    style={{ width: '100%' }}
                    placeholder="请选择二级分类"
                    label="二级分类"
                    name='parentId2'
                    disabled={!parentId}
                    params={{ parentId }}
                    request={getList1}
                  />
                );
              }}
            </ProFormDependency>
          </Col>
          <Col span={12}>
            <Input.Search
              style={{ width: '100%', marginBottom: 20 }}
              placeholder="关键字"
              enterButton='查询'
              onSearch={onSearchSelect}
              onPressEnter={(e) => onSearchSelect(e?.target?.value)}
            />
          </Col>
        </Row>
      </ProForm>
    <div style={{height:'50vh',padding:'15px',overflowY:'auto'}}>
      <div>
        <h3>常用西药</h3>
        <List
          pagination={{
            position: "bottom",
            hideOnSinglePage: true,
          }}
          dataSource={hotDataList}
          renderItem={(item: any, index) => {
            const isChangeItem = selectList?.find((li) => li?.medicineId == item?.id)

            console.log('isChangeItem :>> ', isChangeItem);
            return (
              <List.Item
                className={styles.listItem}
                actions={[
                  <Space >
                    <span>数量：</span>
                    <InputNumber
                      min={0}
                      max={100}
                      value={isChangeItem?.quantity || 0}
                      onChange={(e) => onChangeNumber(e, item)}
                      style={{ width: 80 }}
                    />
                  </Space>,
                ]}
                key={index}
              >
                <List.Item.Meta
                  title={
                    [
                      <Space key='tyPatientName'>
                        <div>{item?.name}</div>
                      </Space>,
                    ]
                  }
                />
              </List.Item>
            )
          }}
        />
        <h3>西药列表</h3>
        <List
          pagination={{
            position: "bottom",
            hideOnSinglePage: true,
          }}
          dataSource={data}
          renderItem={(item: any, index) => {
            const isChangeItem = selectList?.find((li) => li?.medicineId == item?.id)
            const curItem = Array.isArray(isChangeItem) && isChangeItem?.length > 0 && isChangeItem[0]
            return (
              <List.Item
                className={styles.listItem}
                actions={[
                  <Space >
                    <span>数量：</span>
                    <InputNumber
                      min={0}
                      max={100}
                      value={isChangeItem?.quantity || 0}
                      onChange={(e) => onChangeNumber(e, item)}
                      style={{ width: 80 }}
                    />
                    <span>库存：{item.inventoryCount}</span>
                  </Space>,
                ]}
                key={index}
              >
                <List.Item.Meta
                  title={
                    [
                      <Space key='tyPatientName'>
                        <div>{item?.name}</div>
                      </Space>,
                    ]
                  }
                />
              </List.Item>
            )
          }}
        />
      </div>
    </div>
    <Button type="primary" onClick={onKeep}>保存</Button>
    </div>
  );
};
export default WesternMedicineList;

